package cfca.paperless.client.servlet._8_local;

import java.io.File;
import java.util.ArrayList;

import org.apache.commons.io.FileUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import cfca.paperless.client.bean.MultiDataBean;
import cfca.paperless.client.servlet.PaperlessConfig;
import cfca.paperless.client.util.IoUtil;
import cfca.paperless.client.util.PaperlessUtil;
import cfca.paperless.client.util.PdfUtil;
import cfca.sadk.algorithm.common.Mechanism;

/**
 * @Description PDF自动化合成多媒体数据接口，使用示例。
 * 1，操作对象为本地待处理的单个PDF文件，所有操作都在客户本地完成。
 * 2，合成内容包含：图片、录音等。 
 * 3，返回成功合成内容的PDF文件。
 * 
 * @Author dell
 * @Date 2017-12-12
 * @CodeReviewer TODO
 */
public class SynthesizeAutoMultiPdfLocalTest {

    public static void main(String[] args) throws Exception {

        System.out.println("SynthesizeAutoMultiPdfLocalTest START");

        String pdfFilePath = "./TestData/file.pdf";
        String pdfSuffix = IoUtil.getFileNameSuffix(pdfFilePath);
        if(!PaperlessConfig.PDF_FILE_SUFFIX.equals(pdfSuffix)){
            throw new Exception("所选文件不是pdf文件");
        }
        
        // 待合成业务数据的PDF文件
        byte[] pdfFileData = FileUtils.readFileToByteArray(new File(pdfFilePath));

        // 需要合成到pdf的多媒体数据，多媒体数据包括图片、录音等
        byte[] handwritingImage = FileUtils.readFileToByteArray(new File("./TestData/zhangfei.png"));// 手写签名图片
        byte[] handwritingData = handwritingImage;// 假定为手写签名笔记数据
        byte[] identificationFront = FileUtils.readFileToByteArray(new File("./TestData/1.png"));// 身份证正面照片
        byte[] identificationBack = FileUtils.readFileToByteArray(new File("./TestData/2.png"));// 身份证背面照片

        // 多媒体信息数据，多媒体信息名称，多媒体信息描述，type取值：0=不放到pdf文档中（需要客户自己保存）；1=注释方式；2=附件方式
        MultiDataBean handwritingImageBean = new MultiDataBean(handwritingImage, "handwritingImage.png", "手写签名图片", "2");
        MultiDataBean handwritingDataBean = new MultiDataBean(handwritingData, "handwritingData.dat", "手写签名笔记数据", "2");
        MultiDataBean identificationFrontBean = new MultiDataBean(identificationFront, "identificationFrontImage.png", "身份证正面照片", "2");
        MultiDataBean identificationBackBean = new MultiDataBean(identificationBack, "identificationBackImage.png", "身份证背面照片", "2");
        
        ArrayList<MultiDataBean> multiDataList = new ArrayList<MultiDataBean>();
        multiDataList.add(handwritingImageBean);
        multiDataList.add(handwritingDataBean);
        multiDataList.add(identificationFrontBean);
        multiDataList.add(identificationBackBean);

        // 校验PDF文件
        if (multiDataList != null && multiDataList.size() > 0) {
            int sigLen = PdfUtil.getPdfSignatureLength(pdfFileData);
            if(sigLen > 0) {
                throw new Exception("pdf中已经存在签名不能继续合成数据");
            }
        }
        // 合成多媒体文件
        for (MultiDataBean multiDataBean : multiDataList) {
            String type = multiDataBean.getType();
            String fileName = multiDataBean.getFileName();
            byte[] fileData = multiDataBean.getMultiData();
            
            if ("1".equals(type)) {
                pdfFileData = PdfUtil.compoundPdfDataByAnnotation(pdfFileData, fileData, fileName, "");
                System.out.println("type=1多媒体作为注释合成：" + fileName);
            } else if ("2".equals(type)) {
                pdfFileData = PdfUtil.compoundPdfDataByAttachment(pdfFileData, fileData, fileName);
                System.out.println("type=2多媒体作为附件合成：" + fileName);
            } else if ("0".equals(type)) {
                System.out.println("type=0不合成：" + fileName);
            } else {
                throw new Exception("type取值异常。type:" + type);
            }
        }
        
        
        
        String[] proofHashAndMultiData = PaperlessUtil.getProofHashAndMultiData(multiDataList);
        
        String proofHashXmlString = proofHashAndMultiData[0];
        String multiDataString = "[" + proofHashAndMultiData[1] + "]";
        
        System.out.println(proofHashXmlString);
        System.out.println(multiDataString);

        // 计算pdf内容hash
        String pdfContentHash = PdfUtil.calculatePdfContentHash(pdfFileData, new Mechanism(Mechanism.SHA1));
        proofHashXmlString = addProofToXml(proofHashXmlString, "pdfHash.pdf", pdfContentHash);
        
        // 合成proofHash
        pdfFileData = PdfUtil.compoundPdfDataByAttachment(pdfFileData, proofHashXmlString.getBytes(), "proofHash.xml");
        
        
        
        System.out.println("SynthesizeAutoMultiPdfLocalTest END OK");
        IoUtil.write("./TestData/output/SynthesizeAutoMultiPdfLocalTest.pdf", pdfFileData);

    }

    private static String addProofToXml(String xmlContent, String fileName, String hash) throws DocumentException {
        Document document = DocumentHelper.parseText(xmlContent);
        Element root = document.getRootElement();
        Element newElement = root.addElement("Proof");
        newElement.addAttribute("fileName", fileName);
        newElement.addAttribute("hash", hash);
        return document.asXML();
    }

}
